import os

from django.conf import settings
from django.http import JsonResponse

from XApiTestServer.utils.common import *
from XApiTestServer.utils.response import *

import logging


logger = logging.getLogger('XApiTestServer')


def show_logs(request):
    type = request.GET.get('type')
    ret = {}
    # type值为0时是系统日志，值为其他时为debug日志
    if type == '0':
        log_file = os.path.join(settings.BASE_DIR, "logs", "all.log")
        ret["type"] = u"系统日志"
    else:
        log_file = os.path.join(settings.BASE_DIR, "logs", "debugtalk.log")
        ret["type"] = u"debugtalk日志"
    log = []

    if os.path.exists(log_file):
        pass
    else:
        response_body = LOG_NOT_EXISTS
        return JsonResponse(response_body)

    with open(log_file, 'r', encoding='utf-8') as pf:
        type = 'error'
        for line in pf.readlines():
            if line != '\n':
                obj = {}
                if '[ERROR]' in line:
                    type = 'error'
                elif '[INFO]' in line:
                    type = 'info'
                obj["type"] = type
                obj["content"] = line.strip('\n')
                log.append(obj)
    ret['logs'] = log
    response_body = SUCCESS_INFO
    response_body['data'] = ret
    return JsonResponse(response_body)
